﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectRecycleActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var user = this.Context.Token.Identity();
            var Id = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Id", g =>
            {
                var webr = UMC.Web.WebResource.Instance();
                var form = request.SendValues ?? new UMC.Web.WebMeta();

                int limit = UMC.Data.Utility.IntParse(form["limit"], 25);
                int start = UMC.Data.Utility.IntParse(form["start"], 0);

                string sort = form["sort"];
                string dir = form["dir"];


                var Project = UMC.Data.Utility.UInt64Parse(form["Project"]);

                var Keyword = (form["Keyword"] as string ?? String.Empty);
                var search = new Subject() { project_id = Project, Status = -2 };
                if (String.IsNullOrEmpty(Keyword) == false)
                {
                    search.Title = Keyword;

                }
                var subs = new List<Subject>();
                var uids = new List<Guid>();

                int nextIndex;

                UMC.Data.Utility.Each(DataFactory.Instance().Search(search, start, out nextIndex, limit), dr =>
                {
                    subs.Add(dr);
                    if (dr.user_id.HasValue)
                    {
                        if (uids.Exists(u => u == dr.user_id.Value) == false)
                        {
                            uids.Add(dr.user_id.Value);
                        }
                    }
                    if (dr.last_user_id.HasValue)
                    {
                        if (uids.Exists(u => u == dr.last_user_id.Value) == false)
                        {
                            uids.Add(dr.last_user_id.Value);
                        }
                    }

                });
                var cates = new List<Attention>(DataFactory.Instance().Attention(uids.ToArray()));

                var data = new System.Data.DataTable();
                data.Columns.Add("id");
                data.Columns.Add("title");
                data.Columns.Add("desc");
                data.Columns.Add("time");
                data.Columns.Add("reply");
                data.Columns.Add("look");
                data.Columns.Add("favs");
                data.Columns.Add("lastid");
                data.Columns.Add("lastTime");
                data.Columns.Add("lastName");
                data.Columns.Add("lastSrc");
                data.Columns.Add("postid");
                data.Columns.Add("poster");
                data.Columns.Add("postsrc");
                data.Columns.Add("project");
                data.Columns.Add("projectItem");
                foreach (var sub in subs)
                {
                    var user1 = cates.Find(d => d.Id == sub.user_id) ?? new Attention();

                    var user2 = cates.Find(d => d.Id == sub.last_user_id) ?? new Attention();
                    data.Rows.Add(sub.Id, sub.Title, sub.Description, sub.ReleaseTime.HasValue ? UMC.Data.Utility.GetDate(sub.ReleaseTime) : "未发布"
                        , sub.Reply ?? 0, sub.Look ?? 0, sub.Favs ?? 0, sub.last_user_id, UMC.Data.Utility.GetDate(sub.LastDate), user2.Alias, webr.ImageResolve(request.Url, sub.last_user_id ?? Guid.Empty, "1", 4), sub.user_id, user1.Alias, webr.ImageResolve(request.Url, sub.user_id ?? Guid.Empty, "1", 4),
                        sub.project_id, sub.project_item_id);
                }
                var hashc = new System.Collections.Hashtable();
                hashc["next"] = nextIndex > 0;
                if (data.Rows.Count == 0 && start == 0)
                {
                    hashc["msg"] = "回收站是空的";
                }
                else
                {
                    hashc["data"] = data;
                    hashc["start"] = nextIndex;
                }
                response.Redirect(hashc);
                return this.DialogValue("none");
            })).Value;

            var subt = DataFactory.Instance().Subject(Id);// subEntity.Single(new Subject { project_id = Guid.Empty, Id = Guid.Empty, Title = String.Empty, user_id = Guid.Empty });
            var project = DataFactory.Instance().Project(subt.project_id.Value);

            var member = DataFactory.Instance().ProjectMember(subt.project_id.Value, user.Id.Value);

            if (member != null)
            {
                switch (member.AuthType)
                {
                    case WebAuthType.Admin:
                    case WebAuthType.User:
                        break;
                    default:
                        this.Prompt("您未有管理回收站的权限");
                        break;
                }

            }
            else
            {
                this.Prompt("您未有管理回收站的权限");
            }

            var arg = request.Arguments;
            var Type = this.AsyncDialog("Type", g =>
            {
                var optls = new Web.UISheetDialog();
                optls.Title = "回收站";
                optls.Put("还原", "Restore");
                optls.Put("删除", "Del");



                return optls;
            });
            switch (Type)
            {
                case "Del":
                    DataFactory.Instance().Delete(new Subject { Id = subt.Id.Value });
                    DataFactory.Instance().Delete(new SubjectContent { Id = subt.Id.Value });
                    var ax = DataFactory.Instance().Attention(subt.user_id.Value) ?? new Attention { Id = subt.user_id.Value };
                    DataFactory.Instance().Put(new Attention
                    {
                        Id = subt.user_id.Value,
                        SubjectTotal = (ax.SubjectTotal ?? 0) - 1
                    });
                    DataFactory.Instance().Put(new Project
                    {
                        Id = project.Id,
                        SubjectTotal = (project.SubjectTotal ?? 0) - 1
                    });
                    this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Portfolio.Change").Put("Sub", Id), true);
                    return;
            }

            var sid = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("PortfolioId", request.Model, "Portfolio", new Web.WebMeta().Put("Project", subt.project_id))).Value;

            var Portfolio = DataFactory.Instance().Portfolio(sid);

            var projectItem = DataFactory.Instance().ProjectItem(Portfolio.project_item_id.Value);

            DataFactory.Instance().Put(new Subject()
            {
                Id = subt.Id,
                LastDate = DateTime.Now,
                portfolio_id = sid,
                Seq = UMC.Data.Utility.TimeID(),
                project_id = projectItem.project_id,
                project_item_id = projectItem.Id,
                last_user_id = user.Id,
                Status = -1
            });
            DataFactory.Instance().Put(new ProjectDynamic
            {
                Time = UMC.Data.Utility.TimeSpan(),
                user_id = user.Id,
                Explain = "还原了文档",
                project_id = projectItem.project_id,
                refer_id = Id,
                Title = subt.Title,
                Alias = user.Alias,
                Type = DynamicType.Subject
            });
            DataFactory.Instance().Put(new ProjectItem { Id = projectItem.Id, SubjectTotal = (projectItem.SubjectTotal ?? 0) + 1 });
            this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Portfolio.Change").Put("Sub", Id).Put("Id", sid).Put("Item", new WebMeta().Put("id", subt.Id).Put("text", subt.Title)), true);

        }

    }
}